package com.example.demo.zaqizabatest.调用其它服务接口;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpMethod;
import org.springframework.util.CollectionUtils;

import java.util.Map;

/**
 * @ClassName HttpClient
 * @Author lys4134
 * @Date 2021/08/13 15:37:07
 * @Description HttpClient
 * @Version 1.0
 **/
public class HttpClientDemo {
    @Autowired
    private CloseableHttpClient httpClient;

    @Autowired
    private RequestConfig config;
    private static ObjectMapper objectMapper = new ObjectMapper();

    public static JsonNode post(Map<String,String> headers, String body, HttpMethod method, String url) throws Exception {
        HttpPost post = new HttpPost(url);
        if (!CollectionUtils.isEmpty(headers)){
            for (String key : headers.keySet()){
                post.setHeader(key, headers.get(key));
            }
        }
        String data;
        try {
            data = objectMapper.writeValueAsString(body);
        } catch (JsonProcessingException e) {
            throw new Exception("[请求失败][请求体转JSON失败][" + e.getMessage() + "]");
        }
        StringEntity entity = new StringEntity(data, ContentType.APPLICATION_JSON);
        post.setEntity(entity);
        return http(post, false);
    }

    private static JsonNode http(HttpUriRequest request, boolean again) throws Exception {
        HttpClient httpClient = HttpClientBuilder.create().build();
        HttpResponse response;
        try {
            response = httpClient.execute(request);
        } catch (Exception e) {
            throw new Exception("[请求失败][" + request.getURI() + "][" + e.getMessage() + "]");
        }
        int statusCode = response.getStatusLine().getStatusCode();
        if (200 == statusCode) {
            HttpEntity resEntity = response.getEntity();
            JsonNode root;
            try {
                String res = EntityUtils.toString(resEntity, "UTF-8");
                root = objectMapper.readTree(res);
            } catch (Exception e) {
                throw new Exception("[请求失败][响应体解析失败][" + request.getURI() + "][" + e.getMessage() + "]");
            }
            int code = root.get("code").asInt();
            if (code == 200) {
                return root;
            } else {
                if (again) {
//                    if (code == 401) {
//                        request.setHeader("access_token", token(false, true));
//                        return http(request, false);
//                    }
//                    if (code == 402) {
//                        request.setHeader("access_token", token(true, false));
//                        return http(request, false);
//                    }
                }
                String message = root.get("message").asText();
                throw new Exception("[请求失败][" + request.getURI() + "][" + code + "][" + message + "]");
            }
        } else {
            throw new Exception("[请求失败][" + request.getURI() + "][" + statusCode + "]");
        }
    }

}
